<template>
  <div v-loading="loading" class="formClass hibaoForm column3">
    <el-form ref="ruleForm">
      <div class="position-height">
        <Excel style="text-align: center;margin-top: 40px" :before-upload="beforeUpload" :excel-data.sync="excelData" :file-size-limit="fileSizeLimit" :headers="headers" />
      </div>
      <el-form-item class="bottom-btns add-absolute">
        <el-button type="red" style="float: left;margin-left: 15px" @click.stop="downLoadTemp">下载模版</el-button>
        <el-button type="red" @click.stop="save">保存</el-button>
        <el-button type="cancel" @click.stop="cancel">取消</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>
<script>
import Excel from '@/components/UploadExcel/excel.vue'
import axios from 'axios'
export default {
  name: 'UploadExcel',
  components: { Excel },
  props: {
    type: {
      type: String,
      required: true
    },
    needVerify: {
      tyep: Boolean,
      default: false
    },
    layerid: {
      type: String,
      default: ''
    },
    headers: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      excelData: null,
      fileSizeLimit: 50, // excel文件不超过50MB
      options: [
        { value: 'xlsx' },
        { value: 'xls' }
      ],
      tempType: 'xls',
      publicPath: process.env.BASE_URL
    }
  },
  mounted() {
    this.$store.commit('app/SET_LAYERID', this.layerid)
  },
  methods: {
    downLoadTemp() {
      axios.request({
        // 直接填写public下的路径即可，编译时会自动定位到public文件夹下
        url: '/temps/zh/' + this.type + '.' + this.tempType,
        method: 'get',
        // 设置axios请求的responseType为blob
        responseType: 'blob'
      }).then(res => {
        // 构造一个<a>标签
        const url = window.URL.createObjectURL(res.data)
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url

        // 设置<a>标签的下载动作和文件名，并将标签加入body中
        link.setAttribute('download', this.type + '.' + this.tempType)
        document.body.appendChild(link)

        // 模拟点击
        link.click()
      }).catch(err => {
        console.log(err)
      })
    },
    // 文件上传一些的回调函数
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < this.fileSizeLimit
      if (isLt1M) {
        return true
      }
      this.$message({
        message: this.$t('tip.fileLargeLimit'),
        type: 'warning',
        duration: 1000
      })
      return false
    },
    cancel() {
      this.$layer.close(this.layerid)
    },
    save() {
      console.log(this.excelData)
      console.log('start ====>  ' + this.$moment(new Date()).format('YYYY-MM-DD HH:mm:ss'))
      if (!this.excelData) {
        this.$message({
          message: this.$t('tip.uploadFirst'),
          type: 'warning',
          duration: 1000
        })
        return
      }
      if (this.needVerify) {
        this.$parent.saveImportData(this.excelData.results)
        this.$layer.close(this.layerid) // 关闭弹框
      } else {
        this.loading = true
        // 调用父页面导入方法
        this.$parent.saveImportData(this.excelData.results).then(res => {
          console.log('end ====>  ' + this.$moment(new Date()).format('YYYY-MM-DD HH:mm:ss'))
          if (res) {
            if (res.result === 'success') {
              this.$message({
                message: '导入成功',
                type: 'success',
                duration: 1500
              })
              this.$layer.close(this.layerid) // 关闭弹框
              this.$parent.refresh() // 调用父组件的刷新方法
            } else {
              // 错误提示信息
              const msg = this.$t('tip.importFailed') + ' , ' + this.$t('tip.importErrorLine') + ' :[ ' + res.errLine + ' ], ' + this.$t(res.errMsg)
              this.$message({
                showClose: true,
                message: msg,
                type: 'error',
                duration: 3000
              })
            }
          }
        }).finally(() => {
          this.loading = false
        })
      }
    }
  }
}
</script>
<style scoped>
</style>
